package com.wiz.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.JsonObject;
import com.wiz.common.Constant;

public class MapUtil {
	private static String  JINWEI_CONVERSION_URL="http://apic.map.qq.com/translate/?type=3"
			+ "&points=${lng},${lat}&output=jsonp&pf=jsapi&cb=qq.maps.__svcbi1x9al56.cbi1x9al9l0";
	private static String TENCENT_MAP_URL = "http://apis.map.qq.com/ws/geocoder/v1/?address=${address}&key=${key}";
	/**根据地址得到腾讯经纬度*/
	public static Map<String,Double> tencentJinwei(String address) throws JSONException{
		Map<String,Double> jinwei = new HashMap<String, Double>();
		
		String url = TENCENT_MAP_URL.replace("${address}", address.trim())
				.replace("${key}", Constant.TENCENT_KEY);
		HttpUtil http = new HttpUtil();
		String response = http.getHttpsResponseByGet(url);
		JSONObject json = new JSONObject(response);
		int status = json.getInt("status");
		if(status == 0){
			JSONObject result = json.getJSONObject("result");
			JSONObject location = result.getJSONObject("location");
			jinwei.put("lng", location.getDouble("lng"));
			jinwei.put("lat", location.getDouble("lat"));
			return jinwei;
		}
		return null;
		
	}
	
	
	/**根据百度经纬度得到腾讯经纬度*/
	public static Map<String,Double> JinweiConversion(double lng,double lat) throws Exception{
		String url = JINWEI_CONVERSION_URL.replace("${lng}", String.valueOf(lng))
		.replace("${lat}", String.valueOf(lat));
		HttpUtil http = new HttpUtil();
		System.out.println(url);
		String response = http.getHttpsResponseByGet(url);
		response =response.substring(response.indexOf("(")+1, response.indexOf(")"));
		System.out.println(response);
//		response = "{\"info\":{\"error\":0,\"time\":87},\"detail\":{\"points\":[{\"lng\":104.04718341,\"lat\":30.67519574}]," +
//				"\"query_status\":\"0\",\"server_retcode\":\"0\"}}";
//		response = "{\"info\":{\"error\":4,\"time\":87},\"detail\":{\"errmsg\":\"参数错误\"}}";	
		JSONObject json = new JSONObject(response);
		JSONObject info =  json.getJSONObject("info");
		int error = info.getInt("error");
		JSONObject detail = json.getJSONObject("detail");
		if(error == 0){
			JSONArray points = detail.getJSONArray("points");
			JSONObject point =points.getJSONObject(0);
			System. out.println(point.getDouble("lng"));
	        System. out.println(point.getDouble("lat"));
		}else{
			throw new Exception(detail.getString("errmsg"));
		}
		return null;
		
	}
	
	public static void Convert_BD09_To_GCJ02(double lat, double lng) {
        double x_pi = Math. PI * 3000.0 / 180.0;
        double x = lng - 0.0065, y = lat - 0.006;
        double z = Math. sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        lng = z * Math. cos(theta );
        lat = z * Math. sin(theta );
       
        System. out.println(lng);
        System. out.println(lat);
}
	
	 /** 
     * 返回输入地址的经纬度坐标 
     * key lng(经度),lat(纬度) 
     */  
    public static Map<String,String> getGeocoderLatitude(String address){  
        BufferedReader in = null;  
        try {  
            //将地址转换成utf-8的16进制  
            address = URLEncoder.encode(address.trim(), "UTF-8");  
//       如果有代理，要设置代理，没代理可注释  
//      System.setProperty("http.proxyHost","192.168.1.188");  
//      System.setProperty("http.proxyPort","3128");  
            URL tirc = new URL("http://api.map.baidu.com/geocoder?address="+ address +"&output=json&key=SiEnjNSKI0l7B5ebpjUObQ2I");  
              
            in = new BufferedReader(new InputStreamReader(tirc.openStream(),"UTF-8"));  
            String res;  
            StringBuilder sb = new StringBuilder("");  
            while((res = in.readLine())!=null){  
                sb.append(res.trim());  
            }  
            String str = sb.toString();  
            Map<String,String> map = null;  
            if(StringUtils.isNotEmpty(str)){  
                int lngStart = str.indexOf("lng\":");  
                int lngEnd = str.indexOf(",\"lat");  
                int latEnd = str.indexOf("},\"precise");  
                if(lngStart > 0 && lngEnd > 0 && latEnd > 0){  
                    String lng = str.substring(lngStart+5, lngEnd);  
                    String lat = str.substring(lngEnd+7, latEnd);  
                    map = new HashMap<String,String>();  
                    map.put("lng", lng);  
                    map.put("lat", lat);  
                    return map;  
                }  
            }  
        }catch (Exception e) {  
            e.printStackTrace();  
        }finally{  
            try {  
                in.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return null;  
    }  
    public static void main(String args[]){  
//        Map<String, String> json = MapUtil.getGeocoderLatitude("成都市金牛区永陵公园");  
//        System.out.println("lng : "+json.get("lng"));  
//        System.out.println("lat : "+json.get("lat"));  
//    	Convert_BD09_To_GCJ02(Double.valueOf(json.get("lng")),Double.valueOf(json.get("lat")));
//    	try {
//			JinweiConversion(Double.valueOf(json.get("lng")),Double.valueOf(json.get("lat")));
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
    	try {
			tencentJinwei("成都市金牛区永陵公园");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//    	104.047183
//    	30.675196
//    	
//    	104.04718341,"lat":30.67519574
    }  
}
